<template>
	<view class="productSort copy-data">
		<!-- 判断药房是否有药品数据———>没有数据 -->
		<view style="width: 100%;height: 100vh;background-color: #ffffff;display: flex;align-items: center;"
			v-if="startFlag==1">
			<image :src="picImg" style="width: 100%;height: 50%;" mode="widthFix"></image>
		</view>
		<!-- 有数据 -->
		<view v-else>
			<view class="search-bg">
				<view class="example pad30" style="padding:10rpx 30rpx;">
					<view style="position: relative">
						<image style="
                            width: 40rpx;
                            height: 40rpx;
                            position: absolute;
                            left: 35%;
                            top: 13rpx;
                        " src="../../static/images/search.png"></image>
						<input placeholder-style="marginLeft:20rpx" class="inputStyle" :disabled="true" type="text"
							@click="medicalList" :placeholder="placeholder" />
					</view>
				</view>
			</view>
			<view>
				<view class="aside" style="margin-bottom: 50rpx">
					<!--      左分类列表-->
					<view class="item acea-row row-center-wrapper" v-for="(item, index) in productList" :key="index"
						:class="item.id == navActive ? 'on' : ''" @click="tap(index, item.id)">
						<text>{{ item.name }}</text>
					</view>
				</view>

				<view class="conter">
					<view v-if="isBarTitle" class="durgName"
						style="text-align: right; color: red; line-height: 44rpx;    height: 44rpx;position:fixed;top:94rpx;z-index: 99;background: #ffffff;width: 70%;">
						注：仅带有
						<image class="yibaoTips" src="../../static/images/chs.png" />
						<!-- <text class="yibaoTips">医保</text> -->
						标志的药品支持医保支付
					</view>
					<scroll-view scroll-y="true" @scrolltolower="lower()" style="padding-top:50rpx;"
						:style="{ height: windowHeight + 'px' }" scroll-with-animation="true">
						<view v-if="listData.length > 0" class="listw">
							<view class="list" v-for="(item, index) in listData" :key="index">
								<!--  商品列表-->
								<view class="durgList" style="display: flex" @click="goCart(item.id)">
									<view class="durgImg">
										<image :src="item.image"></image>
									</view>
									<view class="durgInfo">
										<view class="durgName">
											<image class="yibaoTips"
												v-if='(item.medicalItemCode || item.medicalItemCode2) && item.medicalFlag == 1'
												src="../../static/images/chs.png" />
											<!-- <text
                                        class="yibaoTips"
                                        v-if="item.medicalItemCode"
                                        >医保</text
                                    > -->

											<text class="">
												{{ item.name }}
											</text>
										</view>
										<view class="price">
											<view class="gray_font" style="
                                            margin-top: 7rpx;
                                            font-size: 26rpx;
                                        ">
												<text>规格：{{
												    item.specification || '暂无规格'
												}}</text>
											</view>
											<view class="gray_font" style="
                                            float: right;
                                            margin-top: 7rpx;
                                            font-size: 26rpx;
                                        ">库存：{{ item.stock || '0' }}</view>
										</view>
										<!--                  <view class="headline gray_font">一次1-2粒，每日两次</view>-->
										<view style="display: flex">
											<view class="price">
												<view class="priceMoney">
													<text>￥{{
													    item.price.toFixed(2)
													}}</text>
												</view>
											</view>
											<!-- <text class="" selectable="false" space="false" decode="false" @click="share">
												分享
											</text> -->
											<view style="
                                            width: 130rpx;
                                            margin-top: 15rpx;
                                            text-align: center;
                                        " @click.stop="getMsg(item)" class="drugs_adjustment" size="mini"
												v-if="item.stock > 0">
												加购
											</view>
										</view>
									</view>
								</view>
							</view>
						</view>
						<view class="noInfo_Img" v-else>
							<image src="../../static/images/icon_lack_message@2x.png"></image>
							<view v-if="!isLogin" class="toLogin">
								<text class="" @click="toLogin">
									查看更多商品，请先
									<text class="greenFont">登录</text>
								</text>
							</view>
						</view>
						<uni-load-more :status="statusLoad" :content-text="contentText" v-if="showLoadMore" />
					</scroll-view>
				</view>
			</view>
			<uni-popup ref="popup">
				<view style="
                    padding: 20rpx;
                    background-color: #ffffff;
                    border-top-right-radius: 15rpx;
                    border-top-left-radius: 15rpx;
                ">
					<view class="icon_close">
						<image @click="closeXQ" style="width: 50rpx; height: 50rpx; float: right"
							src="../../static/images/icon_close_gray.png"></image>
					</view>
					<view class="medicalinner_border">
						<view class="medicalinner_img">
							<image style="width: 100%; height: 100%" :src="drugData.image"></image>
						</view>
						<view style="margin-left: 25rpx">
							<view class="medicalName" style="font-size: 33rpx; margin-top: 10rpx">
								{{ drugData.name ? drugData.name : '' }}
							</view>
							<view class="price">
								<view class="gray_font" style="margin-top: 7rpx; font-size: 26rpx">
									<text>规格:{{drugData.specification || '暂无规格'}}</text>
								</view>
							</view>
							<view class="medicalprice">
								￥{{
								    drugData.price ? drugData.price.toFixed(2) : ''
								}}
							</view>
						</view>
					</view>
					<view style="
                        display: flex;
                        justify-content: space-between;
                        margin-top: 30rpx;
                    ">
						<view style="
                            line-height: 60rpx;
                            font-size: 33rpx;
                            color: #999999;
                        ">
							数量
						</view>
						<view>
							<uni-number-box :min="1" ref="usernameInput" @change="changecount" />
						</view>
					</view>
					<button v-if="btnsign == 1" @click="addCart" class="btn_appointment arc_button" type="default">
						加入购物车
					</button>
				</view>
			</uni-popup>
			<!-- <view class="uni-p-b-98"></view> -->
			<view class="goods-carts" @click="onClick">
				<uni-badge class="uni-badge-left-margin" style="width: 120rpx" :text="cartNumber" absolute="rightTop"
					size="small" type="error">
					<image src="../../static/images/shopCar.png"></image>
				</uni-badge>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		drugList,
		getStoreStartOpen
	} from '@/api/prescribing.js';
	import {
		getCateList,
		getUserDrugList
	} from '@/api/user.js';
	import {
		cartAdd,
		CartNum
	} from '@/api/order.js';
	import store from '@/store';
	export default {
		components: {},
		data() {
			return {
				isBarTitle: true,
				placeholder: '搜索药品',
				startFlag: '',
				picImg: '',
				options: [{
					icon: 'cart',
					text: '购物车',
					info: 0,
				}, ],
				buttonGroup: [],
				navlist: [],
				productList: [],
				navActive: 1, //左侧分类列表数据的id
				number: '',
				height: 0,
				hightArr: [],
				listData: [],
				// 查询参数
				queryParams: {
					categoryId: '',
					storeId: store.state.app.storeId || 0,
					pageNum: 1,
					pageSize: 10,
					searchName: '',
				},
				//分页开始
				showLoadMore: false,
				statusLoad: 'more',
				contentText: {
					contentdown: '查看更多',
					contentrefresh: '加载中...',
					contentnomore: '没有更多',
				},
				total: 0, //总条数
				nowCount: 0, //当前累计显示条数
				toView: '',
				windowHeight: 0,
				chooseHeight: 0,
				drugSort: '',
				medicalid: '',
				drugData: {},
				Medicalcount: 1,
				btnsign: '',
				cartNumber: '',
				isLogin: false, //是否登录
			};
		},
		onShow() {
			let isDetail = store.state.app.drugDetail || false;
			let categoryId = store.state.app.categoryId;
			let storeName = store.state.app.storeName;
			uni.setNavigationBarTitle({
				title: storeName || '商品列表', //设置标题
			});
			this.getStoreStartOpen()
			// this.listData = [];
			this.nowCount = 0;
			this.total = 0;
			this.queryParams.categoryId = categoryId || '1';
			this.navActive = categoryId || 1;
			this.isLogin = this.$store.getters.isLogin;
			if (this.$store.getters.isLogin) {

				if (isDetail != true) {
					// 不从详情中返回来的 
					this.queryParams.pageNum = 1;
					this.getCartCount();
					this.getAllCategory(); //种类
				}

			}
			this.showLoadMore = false

			let _this = this;
			uni.getSystemInfo({
				success: function(res) {
					_this.windowHeight = res.windowHeight * 0.92;
				},
			});
			// 返回以后将是否为从详情中返回的标识改为false
			if (isDetail == true) {
				this.$store.commit('SET_DRUG_DETAIL', false); //是否从药品详情中返回的标识
			}
			this.setBarTitle(this.$store.state.app.flag);
		},

		onPullDownRefresh() {
			this.getCartCount();
			this.getAllCategory();
			this.showLoadMore = false

			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		onLoad(options) {
			// this.listData = []
			// this.nowCount = 0
			// this.total = 0
			// this.listData = []
			//  this.getAllCategory()
			//  this.getCartCount() //购物车数量
			//  let _this = this
			//  uni.getSystemInfo({
			//    success: function (res) {
			//      _this.windowHeight = res.windowHeight * 0.92
			//    },
			//  })

		},
		onReady() {
			// this.$nextTick(()=>{
			// 	const query = uni.createSelectorQuery();
			// 	query.select('#tabbar').boundingClientRect(data => {
			// 		console.log(data)
			// 	}).exec();
			// });
		},
		methods: {
			setBarTitle(expressFlag) {
				if (expressFlag === '1') {

					this.isBarTitle = false

					this.placeholder = '搜索商品';
				} else {
					this.isBarTitle = true
					this.placeholder = '搜索药品';
				}

			},
			// 判断药店库存情况 
			getStoreStartOpen() {
				let storeId = store.state.app.storeId
				getStoreStartOpen(storeId).then((res) => {
					// console.log(res, "判断药店是否有数据")
					this.picImg = res.data.picImg
					this.startFlag = res.data.startFlag
				})
			},
			toLogin() {
				uni.navigateTo({
					url: '/pagesSub/index/index'
				})
			},
			lower() {
				//在1s后执行一次该函数
				setTimeout(() => {
					if (this.nowCount > 0 && this.nowCount >= this.total) {
						this.statusLoad = 'noMore';
					} else {
						this.showLoadMore = true;
						this.statusLoad = 'loading';
						this.druginfo();
					}
				}, 1000);
			},
			goCart(id) {
				uni.navigateTo({
					url: `/pagesSub/homePage/prescribing/mallMessage?medicalid=${id}`,
				});
			},
			onClick() {
				uni.navigateTo({
					url: `/pagesSub/shopCar/index`,
				});
			},
			closeXQ() {
				this.Medicalcount = 1;
				// console.log(this.Medicalcount);
				this.$refs['usernameInput'].reset();
				this.$refs.popup.close();
			},
			//更改数量
			changecount(e) {
				this.Medicalcount = e;
			},
			getMsg(item) {
				let _this = this;
				// _this.medicalid = id
				console.log(item);
				_this.drugData = item;
				this.btnsign = 1;
				this.$refs.popup.open('bottom');
			},
			//加入购物车
			addCart() {
				let _this = this;
				uni.showLoading({
					title: '加载中',
				});
				console.log('数量++', _this.Medicalcount);
				cartAdd({
						productId: _this.drugData.id,
						countNum: _this.Medicalcount, //数量
						type: 1, //1 添加数量，2 减少数量
						uid: store.state.app.uid,
						// doctorId: store.state.app.serviceUid, //医生id
						storeId: store.state.app.storeId, //药店id
					})
					.then((res) => {
						if (res.code == 200) {
							this.getCartCount();
							this.$refs.popup.close();
							uni.showToast({
								title: '添加成功',
								icon: 'none',
								duration: 3000,
							});
							_this.Medicalcount = 1;
							this.$refs['usernameInput'].reset();
							uni.hideLoading();
						}
					})
					.catch((err) => {
						uni.hideLoading();
						uni.showToast({
							title: err,
							icon: 'none',
							duration: 3000,
						});
					});
			},
			// 获取购物车数量
			getCartCount() {
				let _this = this;
				let storeId = store.state.app.storeId; //药店id
				// console.log('缓存里的storeId-------', storeId);

				// uni.showLoading({
				//   title:'加载中'
				// })
				CartNum(storeId)
					.then((res) => {
						_this.options[0].info = res.data;
						_this.cartNumber = res.data;
						// console.log(_this.options[0].info+'角标');
						// uni.hideLoading()
					})
					.catch((res) => {
						// uni.hideLoading()
					});
			},
			tap(index, id) {
				this.$store.commit('SET_CATEGORY_ID', id); //将点击的categoryId存到缓存中
				// this.toView = id;
				this.navActive = id; // index; navActive为列表数据的id
				this.queryParams.categoryId = id;
				this.queryParams.pageNum = 1;
				this.nowCount = 0;
				this.listData = []
				this.druginfo();
			},
			// 侧边栏分类列表
			getAllCategory() {
				let that = this;

				let storeId = store.state.app.storeId; //药房id
				if (this.$store.state.app.flag === '1') {


					that.productList = [{
						id: 32,
						name: '日化产品'
					}]
					this.navActive =
						32;
					that.queryParams.categoryId =
						32;
					//		  console.log('*************',that.queryParams.categoryId)
					//          console.log(that.queryParams.categoryId)
					that.druginfo();

				} else {

					console.log(storeId, '药店id999--');
					getCateList(storeId)
						.then((res) => {
							that.productList = res.data;
							this.navActive = store.state.app.categoryId ||
								res.data[0].id;
							that.queryParams.categoryId = store.state.app.categoryId ||
								res.data[0].id;
							//		  console.log('*************',that.queryParams.categoryId)
							//          console.log(that.queryParams.categoryId)
							that.druginfo();
						})
						.catch((res) => {
							uni.hideLoading();
						});
				}





			},

			// 侧边栏选中项的药品列表
			druginfo() {
				let _this = this;
				_this.queryParams.storeId = store.state.app.storeId || '0'; //没有绑定药店时默认传0 防止接口报错
				let newData;
				let listData = _this.listData;
				let nowCount = _this.nowCount;
				let pageNum = _this.queryParams.pageNum;
				//	  console.log('_this.nowCount:',_this.nowCount,'_this.total：',_this.total)
				if (_this.nowCount > 0 && _this.nowCount >= _this.total) return;
				// uni.showLoading({title: '加载中'});
				getUserDrugList(_this.queryParams)
					.then((res) => {
						let listNew = [];
						_this.showLoadMore = false;

						if (_this.queryParams.pageNum != 1) {
							newData = listData.concat(res.rows);
						} else {
							newData = res.rows;
						}
						_this.$set(_this, 'listData', newData); //使用$set可以避免this直接赋值，在组件上【有时】不及时生效的问题（偶尔会出现）
						//设置分页
						_this.total = res.total;
						_this.queryParams.pageNum = pageNum + 1;
						_this.nowCount = nowCount + res.rows.length;
						// if (pageNum == 1 && res.rows.length <= 0) {
						// }

						// uni.hideLoading();
					})
					.catch((res) => {
						// uni.hideLoading();
					});
			},
			cancelClick() {
				this.nowCount = 0;
				this.total = 0;
				this.queryParams.pageNum = 1;
				this.queryParams.searchName = '';
				this.druginfo();
			},
			search(e) {
				console.log('^^^^', e);
				let _this = this;
				_this.queryParams.searchName = e.value;
				_this.nowCount = 0;
				_this.total = 0;
				_this.queryParams.pageNum = 1;
				this.druginfo();
			},
			medicalList() {
				if (this.$store.getters.isLogin) {
					uni.navigateTo({
						url: '/pages/homePage/searchList',
					});
				} else {
					uni.navigateTo({
						url: '/pagesSub/index/index',
					});
				}
			},
		},
	};
</script>

<style lang="scss" scoped>
	@import '@/static/css/style.css';

	.search-bg {
		position: fixed;
		height: 104rpx;
		width: 100%;
		top: -2rpx;
		z-index: 99;
		background: #f7f7f7
	}

	.productSort .header {
		width: 100%;
		height: 100rpx;
		background-color: #fff;
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		z-index: 9;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.productSort .header .input {
		width: 700rpx;
		height: 60rpx;
		background-color: #f5f5f5;
		border-radius: 50rpx;
		box-sizing: border-box;
		padding: 0 25rpx;
	}

	.productSort .header .input .iconfont {
		font-size: 35rpx;
		color: #555;
	}

	.productSort .header .input .placeholder {
		color: #999;
	}

	.productSort .header .input input {
		font-size: 26rpx;
		height: 100%;
		width: 597rpx;
	}

	.productSort .aside {
		position: fixed;
		width: 24%;
		left: 0;
		top: 0;
		background-color: #f7f7f7;
		overflow-y: auto;
		overflow-x: hidden;
		height: auto;
		margin-top: 102rpx;
		/* 兼容 IOS<11.2 */
		bottom: calc(100rpx+ constant(safe-area-inset-bottom));
		/* 兼容 IOS>11.2 */
		bottom: calc(100rpx + env(safe-area-inset-bottom));
	}

	.productSort .aside .item {
		height: 100rpx;
		width: 100%;
		font-size: 26rpx;
		color: #424242;
	}

	.productSort .aside .item.on {
		background-color: #fff;
		border-left: 4rpx solid #fc4141;
		width: 100%;
		text-align: center;
		color: #fc4141;
		font-weight: bold;
	}

	.productSort .conter {
		margin: 102rpx 0 0 180rpx;
		padding: 0 14rpx;
		background-color: #fff;
	}

	// .productSort .conter .listw {
	//     // padding-top: 18rpx;
	// }

	.productSort .conter .listw .title {
		height: 90rpx;
	}

	.productSort .conter .listw .title .line {
		width: 100rpx;
		height: 2rpx;
		background-color: #f0f0f0;
	}

	.productSort .conter .listw .title .name {
		font-size: 28rpx;
		color: #333;
		margin: 0 30rpx;
		font-weight: bold;
	}

	.productSort .conter .list {
		flex-wrap: wrap;
	}

	.productSort .conter .list .item {
		width: 177rpx;
		margin-top: 26rpx;
	}

	.productSort .conter .list .item .picture {
		width: 120rpx;
		height: 120rpx;
		border-radius: 50%;
	}

	.productSort .conter .list .item .picture image {
		width: 100%;
		height: 100%;
		border-radius: 50%;
	}

	.productSort .conter .list .item .name {
		font-size: 24rpx;
		color: #333;
		height: 56rpx;
		line-height: 56rpx;
		width: 120rpx;
		text-align: center;
	}

	.acea-row {
		display: -webkit-box;
		display: -moz-box;
		display: -webkit-flex;
		display: -ms-flexbox;
		display: flex;
		-webkit-box-lines: multiple;
		-moz-box-lines: multiple;
		-o-box-lines: multiple;
		-webkit-flex-wrap: wrap;
		-ms-flex-wrap: wrap;
		flex-wrap: wrap;
	}

	.acea-row.row-center-wrapper {
		-webkit-box-align: center;
		-moz-box-align: center;
		-o-box-align: center;
		-ms-flex-align: center;
		-webkit-align-items: center;
		align-items: center;
		-webkit-box-pack: center;
		-moz-box-pack: center;
		-o-box-pack: center;
		-ms-flex-pack: center;
		-webkit-justify-content: center;
		justify-content: center;
	}

	body,
	html {
		height: unset;
	}

	.line1 {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.durgName {
		font-size: 26rpx;
		margin-top: 8rpx;
		text-overflow: -o-ellipsis-lastline;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		word-break: break-all;
		-webkit-line-clamp: 2;
		line-clamp: 2;
		-webkit-box-orient: vertical;
	}

	.headline {
		font-size: 26rpx;
		margin-top: 5rpx;
	}

	.price {
		width: 100%;
		display: flex;
		justify-content: space-between;
	}

	.price>.priceMoney {
		color: #e26d5f;
		margin-top: 10rpx;
	}

	.drugs_adjustment {
		border-top-right-radius: 40rpx;
		border-bottom-right-radius: 40rpx;
		border-top-left-radius: 40rpx;
		border-bottom-left-radius: 40rpx;
		border: 1rpx solid #f3faff;
		background: -webkit-linear-gradient(#77e2a4, #4ccdbc);
		color: #ffffff;
		height: 55rpx;
		line-height: 55rpx;
		font-size: 26rpx;
		padding: 0 25rpx;
	}

	.toLogin {
		font-size: 26rpx;
		line-height: 58rpx;
		text-align: center;
	}

	.greenFont {
		color: #4ccdbc;
	}

	.durgList {
		display: flex;
		border-bottom: 1px solid #f7f7f7;
		padding: 10rpx 15rpx;
	}

	.durgImg {
		width: 200rpx;
		height: 100rpx;
		margin-top: 20rpx;
	}

	.durgInfo {
		width: 100%;
		margin-left: 15rpx;
	}

	.durgImg image {
		width: 100%;
		height: 100%;
	}

	.uni-p-b-98 {
		height: 100rpx;
		/* 兼容 IOS<11.2 */
		height: calc(100rpx+ constant(safe-area-inset-bottom));
		/* 兼容 IOS>11.2 */
		height: calc(100rpx + env(safe-area-inset-bottom));
	}

	.example-body {
		padding: 0;
		/* #ifndef APP-NVUE */
		display: block;
		/* #endif */
	}

	.goods-carts {
		/* #ifndef APP-NVUE */
		display: flex;
		width: 120rpx;
		/* #endif */
		flex-direction: column;
		position: fixed;
		left: 40rpx;
		right: 0;
		/* #ifdef H5 */
		left: var(--window-left);
		right: var(--window-right);
		/* #endif */
		bottom: 20rpx;
	}

	.preview_content {
		background-color: #ffffff;
		padding: 50rpx 0;
	}

	.preview_content>.title {
		text-align: center;
		font-size: 30rpx;
	}

	.numberBox {
		display: inline-block;
		margin-bottom: 80rpx;
		margin-top: 20rpx;
	}

	.content {
		text-align: center;
		padding: 50rpx 0;
	}

	.inputStyle_border {
		position: absolute;
		left: 5%;
		width: 90%;
	}

	.inputStyle {
		border-radius: 40rpx;
		height: 65rpx;
		line-height: 65rpx;
		background-color: #ffffff;
		text-align: center;
		font-size: 30rpx;
	}

	.medicalinner_img {
		width: 150rpx;
		height: 140rpx;
		border-radius: 20rpx;
	}

	.medicalinner_border {
		display: flex;
		margin-top: 10rpx;
	}

	.medicalprice {
		font-size: 34rpx;
		color: #eb534c;
		margin-top: 30rpx;
	}

	.medicalName {
		width: 400rpx;
		text-overflow: -o-ellipsis-lastline;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		line-clamp: 2;
		-webkit-box-orient: vertical;
	}

	.btn_appointment {
		margin-top: 30rpx;
		margin-bottom: 30rpx;
		background: -webkit-linear-gradient(#77e2a4, #4ccdbc);
		color: #ffffff;
	}

	.uni-badge-left-margin image {
		width: 85rpx;
		height: 85rpx;
	}
</style>